<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
    <head>
        <th:block th:include="include :: header('用户列表')"/>
        <th:block th:include="include :: layout-latest-css"/>
        <th:block th:include="include :: ztree-css"/>
        <th:block th:include="include :: bootstrap-editable-css"/>
        <th:block th:include="include :: jquery-editable-select"/>

        <style>
            .select {
                border: 1px solid #ddd;
                border-radius: 4px;
                background: transparent;
                outline: none;
                height: 30px;

            }

            .shortselect{
                background:#fafdfe;
                height:28px;
                width:180px;
                line-height:28px;
                border:1px solid #9bc0dd;
                -moz-border-radius:2px;
                -webkit-border-radius:2px;
                border-radius:2px;
            }

            .editable-click, a.editable-click {
                text-decoration: none;
                border-bottom: 0px dashed rgb(0, 136, 204);
                color: #676a6c;
            }

            a.editable-click:hover {
                text-decoration: none;
                /*border-bottom: 1px dashed rgb(0, 136, 204);*/
            }

            .es-list li {
                line-height: 20px;
            }

        </style>
    </head>
    <body class="gray-bg">

        <div class="ui-layout-center">
            <div class="container-div">
                <div class="row">
                    <div class="col-sm-12 search-collapse">
                        <form id="user-form">
                            <input type="hidden" id="deptId" name="deptId">
                            <input type="hidden" id="parentId" name="parentId">
                            <input type="hidden" id="year" name="year">
                            <input type="hidden" id="month" name="month">
                            <div class="select-list">
                                <ul>
                                    <li>
                                        姓名：<input type="text" name="userName"/>
                                    </li>

                                    <li class="date">
                                        <label>排班日期： </label>
                                        <input type="text" class="form-control" id="monthPicker" name="date"
                                               placeholder="yyyy-MM">
                                    </li>
                                    <li>
                                        <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i
                                                class="fa fa-search"></i>&nbsp;搜索</a>
                                        <a class="btn btn-warning btn-rounded btn-sm" onclick="$.form.reset()"><i
                                                class="fa fa-refresh"></i>&nbsp;重置</a>

                                    </li>
                                    <li>
                                        <label>选择月份： </label>
                                        <input type="text" class="form-control" id="monthPicker2"
                                               placeholder="yyyy-MM">

                                    </li>
                                    <li>
                                        <a class="btn btn-primary btn-rounded btn-sm" onclick="setMonthDutyBatch()"><i
                                                class="fa fa-edit"></i>&nbsp;初始化排班</a>
                                        <a class="btn btn-primary btn-rounded btn-sm" onclick="printTable()()"><i
                                                class="fa fa-edit"></i>&nbsp;打印</a>
                                    </li>
                                </ul>
                            </div>
                        </form>
                    </div>

                    <div class="btn-group-sm" id="toolbar" role="group">
                        <label>选择班次：</label>
<!--                        <select id="dutyValue" class="select" th:with="type=${@dict.getType('biz_duty_type')}">-->
<!--                            <option th:each="dict : ${type}" th:text="${dict.dictLabel}"-->
<!--                                    th:value="${dict.dictValue}"></option>-->
<!--                        </select>-->
                        <select id="dutyValue" class="shortselect" th:with="types=${@dutyTypeService.selectBizDutyTypeList()}">
                            <option th:each="t : ${types}" th:text="${t.dutyTypeName}" th:value="${t.dutyTypeName}" ></option>

                        </select>
                        <button class="btn btn-primary" onclick="setDutyByRow()"
                                shiro:hasPermission="system:duty:edit">
                            <i class="fa fa-edit"></i> 修改
                        </button>
                        <a class="btn btn-warning" onclick="$.table.exportExcel()"
                           shiro:hasPermission="system:duty:export">
                            <i class="fa fa-download"></i> 导出
                        </a>

                    </div>

                    <div class="col-sm-12 select-table table-striped">
                        <table id="bootstrap-table"></table>
                    </div>
                </div>
            </div>
        </div>

        <th:block th:include="include :: footer"/>
        <th:block th:include="include :: layout-latest-js"/>
        <th:block th:include="include :: ztree-js"/>
        <th:block th:include="include :: datetimepicker-css"/>
        <th:block th:include="include :: datetimepicker-js"/>
        <th:block th:include="include :: bootstrap-table-editable-js"/>
        <th:block th:include="include :: jquery-editable-select"/>
        <th:block th:include="include :: jQuery-print-js"/>
        <script th:inline="javascript">
            const editFlag        = [[${@permission.hasPermi('system:duty:edit')}]];
            const removeFlag      = [[${@permission.hasPermi('system:duty:remove')}]];
            const dutyOptionDatas = [[${@dict.getType('biz_duty_type')}]]; // 排班类型下拉框
            const prefix          = ctx + "system/duty";

            let dateStr = ''

            const days  = [
                '星期天',
                '星期一',
                '星期二',
                '星期三',
                '星期四',
                '星期五',
                '星期六'
            ]
            var options = {
                url: prefix + "/list",
                createUrl: prefix + "/add",
                updateUrl: prefix + "/edit/{id}",
                removeUrl: prefix + "/remove",
                exportUrl: prefix + "/export",
                importUrl: prefix + "/importData",
                importTemplateUrl: prefix + "/importTemplate",
                // sortName: "createTime",
                // sortOrder: "desc",
                modalName: "排班设置",
                showSearch: false,
                showRefresh: true,
                showToggle: false,
                showColumns: false,
                onClickCell: onClickCell,
                // onEditableSave: onEditableSave,
            };

            $(function () {
                let panehHidden = false;
                if ($(this).width() < 769) {
                    panehHidden = true;
                }
                $('body').layout({initClosed: panehHidden, west__size: 185});

                initDate()
                queryUserList();
                queryDeptTree();

                $('#dutyValue').editableSelect({
                                              effects: 'slide'
                                          });
            });

            function initDate() {
                $("#monthPicker").datetimepicker({
                                                     format: "yyyy-mm",
                                                     startView: 3,
                                                     minView: 3,
                                                     autoclose: true,
                                                 }).on('changeDate', function (event) {
                    event.preventDefault();
                    event.stopPropagation();
                    var year  = event.date.getFullYear()
                    var month = event.date.getMonth() + 1
                    month     = month < 10 ? '0' + month : month;
                    $('#year').val(year)
                    $('#month').val(month)
                    debugger
                    queryUserList()
                });
                var date = new Date()
                $('#monthPicker').datetimepicker('setDate', date); //把要设置的默认值放入new Date()里面
                var year  = date.getFullYear()
                var month = date.getMonth() + 1
                month     = month < 10 ? '0' + month : month;
                $('#year').val(year)
                $('#month').val(month)


                $("#monthPicker2").datetimepicker({
                                                      format: "yyyy-mm",
                                                      startView: 3,
                                                      minView: 3,
                                                      autoclose: true,
                                                  }).on('changeDate', function (event) {
                    event.preventDefault();
                    event.stopPropagation();
                    var year  = event.date.getFullYear()
                    var month = event.date.getMonth() + 1
                    month     = month < 10 ? '0' + month : month;

                });
                var date = new Date()
                $('#monthPicker2').datetimepicker('setDate', date); //把要设置的默认值放入new Date()里面
                var year  = date.getFullYear()
                var month = date.getMonth() + 1
                month     = month < 10 ? '0' + month : month;
            }


            function getDateStr() {
                return $('#year').val() + '-' + $('#month').val()
            }

            function getWeekColumn(dateStr) {
                let month        = new Date(dateStr).getMonth() + 1;
                let year         = new Date(dateStr).getFullYear();
                let startOfMonth = year + '-' + month + '-01'
                let endOfMonth   = year + '-' + month + '-00'
                let startIndex   = new Date(startOfMonth).getDay();
                let endDay       = new Date(year, month, 0).getDate();

                const weekColumn = [{}, {}]

                const dayColumn = [{
                    checkbox: true
                }, {
                    field: 'userName',
                    title: '姓名'
                }]

                const source = dutyOptionDatas.map(d => {
                    let source = {
                        value: d.dictValue,
                        text: d.dictLabel
                    };
                    return source
                })
                for (let i = 1; i <= endDay; i++) {
                    let week   = days[startIndex % 7]
                    let date   = `${month}月${i}日`
                    let column = {
                        title: week,
                        align: 'center',
                        colspan: 1,
                        date: date

                    }
                    weekColumn.push(column)
                    dayColumn.push({
                                       field: `day${i}`,
                                       title: date,

                                       // editable: {
                                       //     type: 'select',
                                       //     title: '请选择班次',
                                       //     emptytext: "--",
                                       //     // mode: "inline",
                                       //     source: source,
                                       //     validate: function (value) {
                                       //         if (!value) {
                                       //             return '请选择班次';
                                       //         }
                                       //     }
                                       // },


                                       // formatter: function (value, row, index) {
                                       //     const val = value<10?'0'+value:value+''
                                       //     console.log(`value=${value}`)
                                       //     return $.table.selectDictLabel(dutyOptionDatas, value);
                                       // },

                                   })
                    startIndex++
                }
                // console.log('----------------------')
                // console.log(colums)
                let colums = [weekColumn, dayColumn];
                return [weekColumn, dayColumn]
            }

            function queryUserList() {
                $.table.destroy();
                options.columns = getWeekColumn(getDateStr())
                $.table.init(options);
            }

            function queryDeptTree() {
                var url     = ctx + "system/dept/treeData";
                var options = {
                    url: url,
                    expandLevel: 2,
                    onClick: zOnClick
                };
                $.tree.init(options);

                function zOnClick(event, treeId, treeNode) {
                    $("#deptId").val(treeNode.id);
                    $("#parentId").val(treeNode.pId);
                    $.table.search();
                }
            }

            $('#btnExpand').click(function () {
                $._tree.expandAll(true);
                $(this).hide();
                $('#btnCollapse').show();
            });

            $('#btnCollapse').click(function () {
                $._tree.expandAll(false);
                $(this).hide();
                $('#btnExpand').show();
            });

            $('#btnRefresh').click(function () {
                queryDeptTree();
            });


            function setDutyByRow() {
                var dutyValue = $('#dutyValue').val()
                var datas     = $("#" + table.options.id).bootstrapTable('getSelections');
                // console.log(`dutyValue=${dutyValue}`)
                // console.log(JSON.stringify(data))
                var ids = datas.map(d => d.id).join(",")
                console.log(`ids=${ids},dutyValue=${dutyValue}`)

                $.post(ctx + 'biz/type/add', {dutyTypeName:dutyValue,type:"1"},function (){
                    updateSelect()
                });

                $.modal.loading("请稍等...");
                $.post(prefix + '/updateByRow', {
                    ids,
                    dutyValue
                }, function (result) {
                    if (result.code == web_status.SUCCESS) {
                        $.modal.msg(result.msg);
                    } else {
                        $.modal.alertError(result.msg);
                    }
                    $.table.refresh()
                    $.modal.closeLoading();
                });
            }

            function onEditableSave(field, row, oldValue, $el) {
                console.log("字段名：" + field + "，当前值：" + row[field] + "，旧值：" + oldValue);
                // console.log(row)
                const dutyObj = {
                    id: row.id,
                    [field]: row[field]
                }
                console.log(dutyObj)
                $.modal.loading("请稍等...");
                $.post(prefix + '/edit', dutyObj, function (result) {
                    if (result.code == web_status.SUCCESS) {
                        $.modal.msg(result.msg);
                    } else {
                        $.modal.alertError(result.msg);
                        $.table.refresh()
                    }
                    $.modal.closeLoading();
                });
            }

            /* 查询表格选择行数据值 */
            function setMonthDutyBatch() {
                var month = $('#monthPicker2').val()
                console.log('>>>>>>month = '+month)
                $.modal.loading("请稍等...");
                $.post(prefix + '/setMonthDutyBatch', {month:month}, function (result) {
                    if (result.code == web_status.SUCCESS) {
                        $.modal.msg(result.msg);
                    } else {
                        $.modal.alertError(result.msg);
                    }
                    $.table.refresh()
                    $.modal.closeLoading();
                });
            }

            function onClickCell(field, value, row, $element){
                const id = row.id
                console.log("单击格name：" + field + " value：" + value+" id:"+id);
                console.log(row);
                if (field == 'userName') return false
                var options = {
                    title: '值班选择',
                    width: "400",
                    height:"400",
                    url: prefix + '/select?id=' + id+"&day="+field+"&userName="+row.userName,
                    callBack: function (index, layero){
                        var body = layer.getChildFrame('body', index);
                        var duty = body.find('#duty').val();

                        console.log('>>>>duty = '+duty)
                        layer.close(index);
                        if (!duty){
                            $.modal.msgError('值班类型未选择')
                            return false;
                        }

                        $.post(ctx + 'biz/type/add', {dutyTypeName:duty,type:"1"},function (){
                            updateSelect()
                        });

                        const dutyObj = {
                            id: row.id,
                            [field]: duty
                        }
                        console.log(dutyObj)
                        $.modal.loading("请稍等...");
                        $.post(prefix + '/edit', dutyObj, function (result) {
                            if (result.code == web_status.SUCCESS) {
                                $.modal.msg(result.msg);
                            } else {
                                $.modal.alertError(result.msg);
                            }
                            $.table.refresh()
                            $.modal.closeLoading();
                        });
                    }
                };
                $.modal.openOptions(options);
            }

            function updateSelect(){
                var template = '<option value="_value">_label</option>'
                $.get(ctx + 'biz/type/getTypes',{},function (res){
                    $('#duty').html('')
                    for (let j=0;j<res.data.length;j++){
                        const type = res.data[j]
                        $('#duty').append(template.replace("_value",type.dutyTypeName).replace("_label",type.dutyTypeName))
                    }
                })
            }

            function printTable(){
                $("#bootstrap-table").print({
                                            addGlobalStyles : true,
                                            stylesheet : null,
                                            rejectWindow : true,
                                            noPrintSelector : ".no-print",
                                            iframe : true,
                                            append : null,
                                            prepend : null
                                        });
            }
        </script>
    </body>
    <!-- 导入区域 -->
    <script id="importTpl" type="text/template">
        <form enctype="multipart/form-data" class="mt20 mb10">
            <div class="col-xs-offset-1">
                <input type="file" id="file" name="file"/>
                <div class="mt10 pt5">
                    <input type="checkbox" id="updateSupport" name="updateSupport" title="如果登录账户已经存在，更新这条数据。">
                    是否更新已经存在的用户数据
                    &nbsp; <a onclick="$.table.importTemplate()" class="btn btn-default btn-xs"><i
                        class="fa fa-file-excel-o"></i> 下载模板</a>
                </div>
                <font color="red" class="pull-left mt10">
                    提示：仅允许导入“xls”或“xlsx”格式文件！
                </font>
            </div>
        </form>
    </script>
</html>